package com.ruix.app.ui.app;

import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;

import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.manager.ClientInfo;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ApiMapper;
import com.ruix.app.model.User;
import com.ruix.app.model.WXUserInfo;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.adapter.GuideAdapter;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.ui.main.MainActivity;
import com.ruix.app.ui.user.BindPhoneActivity;
import com.ruix.app.ui.user.ImportUserInfoActivity;
import com.ruix.app.ui.user.LoginActivity;
import com.ruix.app.widget.XCircleIndicator;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/7/22.
 */

public class GuidanceActivity extends BaseActivity{

    private ViewPager mViewPager;
    private  ViewPaperAdapter adapter;
    private ArrayList pages;
    private  Button login;
    private XCircleIndicator indicator;
    private boolean isLogin = false;

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_guidance;
    }

    @Override
    protected void beforeOnCreate() {
//        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    @Override
    protected boolean isUseNavigaBar() {
        return false;
    }

    @Override
    protected boolean isUseTransStatusBar() {
        return false;
    }

    @Override
    protected void initView() {
        initPages();
        mViewPager = (ViewPager)findViewById(R.id.vp_guide);
        login = (Button) findViewById(R.id.btn_wechat_login);
        indicator = (XCircleIndicator) findViewById(R.id.xCircleIndicator);

        indicator.initData(3, 5);// 设置总共的页数
        indicator.setCurrentPage(0);// 设置当前所在页面
        adapter = new ViewPaperAdapter(pages);
        mViewPager.setAdapter(adapter);
//        mViewPager.setCurrentItem(0);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 2 && !login.isShown()){
                    showLoginButton();
                }
                indicator.setCurrentPage(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //展示登录
    private void showLoginButton(){
        login.postDelayed(new Runnable() {
            @Override
            public void run() {
                login.setVisibility(View.VISIBLE);
                Animation animation = new AlphaAnimation(0.1f, 1.0f);
                animation.setDuration(500);
                login.startAnimation(animation);
            }
        },500);
    }

    private void initPages(){
        pages = new ArrayList();
        View  one=  View.inflate(this,R.layout.item_guide_page,null);
        ImageView oneImage =  (ImageView)one.findViewById(R.id.iv_guide_page_view);
        oneImage.setImageResource(R.drawable.guide_page_one);

        pages.add(one);
        View  two=  View.inflate(this,R.layout.item_guide_page,null);
        ImageView twoImage =  (ImageView)two.findViewById(R.id.iv_guide_page_view);
        twoImage.setImageResource(R.drawable.guide_page_two);
        pages.add(two);

        View  three=  View.inflate(this,R.layout.item_guide_page,null);
        ImageView threeImage =  (ImageView)three.findViewById(R.id.iv_guide_page_view);
        threeImage.setImageResource(R.drawable.guide_page_three);
        pages.add(three);

    }



    @Override
    protected void initLocalData() {
        ClientInfo.setFirstLaunchedApp(RuiApplication.appVersionCode);
        User user = UserManager.getCurrentUser();
        if (user != null){
            isLogin  = user.isHasLogin();
        }
    }

    @Override
    protected void initListener() {
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //微信登录
                if (isLogin){
                    Intent intent = new Intent(GuidanceActivity.this, MainActivity.class);
                    startActivity(intent);
                }else if (isInstallWeiXin()){
                    showLoading();
                    login.setEnabled(false);
                    loginWithWiXin();
                } else {
                    showErrorTip("请安装微信");
                }
            }
        });
    }
    private boolean isInstallWeiXin(){
        return UMShareAPI.get(this).isInstall(this,SHARE_MEDIA.WEIXIN);
    }


    private void loginWithWiXin(){
        UMShareAPI.get(this).doOauthVerify(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                if (map != null && map.get("access_token") != null && map.get("openid") != null){
                    String code = map.get("access_token");
                    String openid = map.get("openid");
                    wechatLogin(code,openid);
                } else {
                    resetView();
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                resetView();
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                resetView();

            }
        });
    }

    private void wechatLogin(final String accessToken, final String openid) {
        RequestFactory.login(accessToken, openid, new RXObserver<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                if (value != null) {
                    JSONObject data = value.optJSONObject("data");
                    if (data != null) {
                        boolean binded = data.optInt("bind_mobie", 0) == 1;
                        if (binded) {
                            getWXUserinfo(accessToken,openid);
                        } else {
                            JSONObject userObject = data.optJSONObject("user");
                            User user = new User().parse(userObject);
                            if (!user.isImportInfo()){
                                Intent intent = ImportUserInfoActivity.newIntent(GuidanceActivity.this, "SplashActivity", null);
                                startActivity(intent);
                            } else {
                                UserManager.sharedInstance().updateUserInfo(user);
                                UserManager.sharedInstance().loginEMClient();
                                loadMain();
                            }
                        }
                    }
                }

            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
                resetView();
            }

            @Override
            public void onComplete() {
                resetView();
            }
        });
    }

    private void bindPhone(WXUserInfo value) {
        Intent intent = new Intent(GuidanceActivity.this, BindPhoneActivity.class);
        intent.putExtra("wxuserinfo",value);
        startActivityForResult(intent,REQUEST_BIND);
    }

    private void resetView(){
        login.setEnabled(true);
        dismissLoading();
    }

    private void getWXUserinfo(String accessToken,String openid){
        showLoading();
        RequestFactory.getWXUserinfo(accessToken, openid, new ApiMapper<WXUserInfo>() {
            @Override
            public WXUserInfo transform(JSONObject response) {
                WXUserInfo wxUserInfo = null;
                if (response != null){
                    wxUserInfo = new WXUserInfo().parse(response);
                }
                return wxUserInfo;
            }
        }, new RXObserver<WXUserInfo>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(WXUserInfo value) {
                bindPhone(value);
            }

            @Override
            public void onError(Throwable e) {
                bindPhone(null);
            }

            @Override
            public void onComplete() {
                dismissLoading();

            }
        });

    }



    private static int REQUEST_BIND= 212;

    private void loadMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        this.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_BIND && resultCode == RESULT_OK){
            loadMain();
            finish();
        }
//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }



    private class ViewPaperAdapter extends PagerAdapter {
        private ArrayList<View> views;

        public ViewPaperAdapter(ArrayList<View> views) {
            this.views = views;
        }

        @Override
        public int getCount() {
            if (views != null) {
                return views.size();
            } else
                return 0;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return (arg0 == arg1);
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView(views.get(position));
        }

        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager) container).addView(views.get(position), 0);
            return views.get(position);
        }
    }
}
